package com.xingxing.Activity;

import android.content.Intent;
import android.os.Handler;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import com.google.gson.Gson;
import com.xingxing.Interface.OkSuccessInterface;
import com.xingxing.Util.APIConfig;
import com.xingxing.Util.CommonUtils;
import com.xuexiang.xui.utils.StatusBarUtils;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xui.widget.progress.loading.ARCLoadingView;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;

import android.annotation.SuppressLint;
import android.os.Message;
import android.view.View;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.xingxing.Util.CommonUtils.OKJsonPost;

public class UseDeviceActivity extends AppCompatActivity {
    Map<String, Object> map;
    private Button btnUseWater;
    private ARCLoadingView mLoadingView;
    private TextView deviceId;
    private TextView location;
    private TextView balance;
    private TextView isUsing;
    private String host = "tcp://43.138.179.149:1883";
    private String userName = "admin";
    private String passWord = "whiteone@lu";
    private String mqtt_id = "mqttdemo11";
    private String mqtt_pub_topic = "water_ox/androidToDevice";
    private String mqtt_sub_topic = "water_ox/device";

    private Handler handler;
    private MqttClient client;
    private MqttConnectOptions options;
    private ScheduledExecutorService scheduler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_use_device);
        Intent intent = getIntent();
        String deviceId = intent.getStringExtra("deviceId");//从intent中读取信息
        String location = intent.getStringExtra("location");//从intent中读取信息
        //设置沉浸式状态栏
        StatusBarUtils.translucent(this);
        //设置黑色字体状态栏
        StatusBarUtils.setStatusBarLightMode(this);
        map = new HashMap<>();
        btnUseWater = (Button) findViewById(R.id.use_water);
        mLoadingView = (ARCLoadingView) findViewById(R.id.arc_loading);
        this.deviceId = (TextView) findViewById(R.id.device_id_value);
        this.location = (TextView) findViewById(R.id.location_value);
        this.balance = (TextView) findViewById(R.id.card_balance_value);
        this.isUsing = (TextView) findViewById(R.id.is_using);
        this.deviceId.setText(deviceId);
        this.mqtt_pub_topic += deviceId;
        this.mqtt_sub_topic += deviceId + "ToAndroid";
        this.location.setText(location);

        updateBalande();

        btnUseWater.setOnClickListener(v -> {
            map.clear();
            if (mLoadingView.isStart()) {
                btnUseWater.setText("开始用水");
                map.put("message", "stop");
                publishMessage(mqtt_pub_topic, new Gson().toJson(map));//发布消息
                isUsing.setVisibility(View.INVISIBLE);
                mLoadingView.stop();
            } else {
                btnUseWater.setText("结束用水");
                map.put("message", "use");
                map.put("userCardId", CommonUtils.GetUserInfo().getUserCardId());
                publishMessage(mqtt_pub_topic, new Gson().toJson(map));//发布消息
                isUsing.setVisibility(View.VISIBLE);
                mLoadingView.start();
            }
        });

        init();
        startReconnect();
        handler = new Handler() {
            @SuppressLint({"SetTextIl8n", "HandlerLeak"})
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1: //开机校验更新回传
                        break;
                    case 2: //反馈回转
                        break;
                    case 3: //MQTT收到消息回传
                        Map<String, Object> map = new HashMap<>();
                        map = new Gson().fromJson(msg.obj.toString(), map.getClass());
                        try {
                            if (map.get("status").toString().equals("stop")) {
                                btnUseWater.setEnabled(true);
                                isUsing.setText("用水中");
                                isUsing.setVisibility(View.INVISIBLE);
                                updateBalande();
                            } else if (map.get("status").toString().equals("using")) {
                                btnUseWater.setEnabled(false);
                                isUsing.setText("其他用户正在使用！");
                                isUsing.setVisibility(View.VISIBLE);
                            }
                        } catch (Exception e) {

                        }
                        break;
                    case 30: //连接失败
                        XToastUtils.info("连接失败");
                        btnUseWater.setEnabled(false);
                        break;
                    case 31: //连接成功
                        try {
                            client.subscribe(mqtt_sub_topic, 0);//订阅
                        } catch (MqttException e) {
                            e.printStackTrace();
                        }
                        break;
                    default:
                        break;
                }
            }
        };
    }

    private void updateBalande() {
        map.clear();
        map.put("userAccount", CommonUtils.GetUserInfo().getUserAccount());
        OKJsonPost(this, new Gson().toJson(map), APIConfig.GetUserBalanceByUserAccount, new OkSuccessInterface() {
            @Override
            public void OnSuccess(String json) {
                map.clear();
                map = new Gson().fromJson(json, map.getClass());
                if (map.get("status").equals("success")) {
                    balance.setText(map.get("userBalance").toString() + "元");
                } else if (map.get("status").equals("error")) {
                    XToastUtils.info("用户余额失败！");
                }
            }
        });
    }

    private void init() {
        try {
            //host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            client = new MqttClient(host, mqtt_id,
                    new MemoryPersistence());
            //MQTT的连接设置
            options = new MqttConnectOptions();
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            //设置连接的用户名
            options.setUserName(userName);
            //设置连接的密码
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            //设置回调
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    //连接丢失后，一般在这里面进行重连
                    System.out.println("connectionLost----------");
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //publish后会执行到这里
                    System.out.println("deliveryComplete---------"
                            + token.isComplete());
                }

                @Override
                public void messageArrived(String topicName, MqttMessage message)
                        throws Exception {
                    //subscribe后得到的消息会执行到这里面
                    System.out.println("messageArrived----------");
                    Message msg = new Message();
                    msg.what = 3;
                    msg.obj = message.toString();
                    handler.sendMessage(msg);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void Mqtt_connect() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (!(client.isConnected())) {
                        client.connect(options);
                        Message msg = new Message();
                        msg.what = 31;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 30;
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }

    private void startReconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!client.isConnected()) {
                    Mqtt_connect();
                }
            }
        }, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS);
    }

    private void publishMessage(String topic, String message2) {
        if (client == null || !client.isConnected()) {
            return;
        }
        MqttMessage message = new MqttMessage();
        message.setPayload(message2.getBytes());
        try {
            client.publish(topic, message);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        client = null;
        super.onDestroy();
    }
}